import "./utils/request.js"
const WxParse = require('./utils/wxParse/wxParse.js');


App({
  onLaunch: function(options) {
    this.authorize(options.query);
  },

  globalData: {
    userInfo: {},
    permitTree: [],
  },

  wxParse: WxParse.wxParse,

  /**
   * 调起授权
   * @param {*} share 分享参数
   */
  authorize(share) {
    share = share || {};
    wx.login({
      success: loginres => {
        wx.getUserInfo({
          success: userres => {
            wx.$http
              .post('/api/weixin/authorize', {
                code: loginres.code,
                iv: userres.iv,
                encryptedData: userres.encryptedData,
                shareId: share.shareId || '',
                source: share.source || '',
              })
              .then(({
                data: res
              }) => {
                wx.setStorageSync('accessToken', res.result.accessToken);
                wx.setStorageSync('permitToken', res.result.permitToken);
                this.getPermitTree();
                this.getWxUserInfo();
                this.webAccess();
              });
          },
          fail: err => {
            let timer = () => {
              setTimeout(() => {
                let pages = getCurrentPages();
                if (pages.length > 0) {
                  wx.setStorageSync('SYS_PREVIOUSPAGE', pages[pages.length - 1]);
                  wx.reLaunch({
                    url: '/pages/login/login',
                  });
                } else {
                  timer();
                }
              }, 250);
            };
            timer();
          },
        });
      }
    });
  },

  /**
   * 获取权限树
   */
  getPermitTree() {
    wx.$http.get('/api/home/menutree').then(({
      data: res
    }) => {
      this.globalData.permitTree = this._buildTreeNode(null, res.result);
    });
  },

  /**
   * 获取用户信息
   */
  getWxUserInfo() {
    wx.$http.get('/api/start/verify').then(({
      data: res
    }) => {
      this.globalData.userInfo = res.result;
    });
  },

  /**
   * 登陆完成后触发
   */
  waitLogin: new Promise(function(resolve, reject) {
    let timer = () => {
      setTimeout(() => {
        let that = getApp();
        if (that !== undefined && Object.getOwnPropertyNames(that.globalData.userInfo).length > 0 && that.globalData.permitTree.length > 0) {
          resolve(that.globalData);
        } else {
          timer();
        }
      }, 250);
    };
    timer();
  }),

  /**
   * 构建权限菜单树
   */
  _buildTreeNode(parent, store) {
    let obj = new Array();
    store.forEach(item => {
      if (!item.ZK_PARENT) {
        item.ZK_PARENT = null;
      }
      if (item.ZK_PARENT === parent) {
        obj.push({
          index: item.ZK_ID,
          path: item.ZK_PATH,
          component: '<router-view></router-view>',
          name: item.ZK_NAME,
          hidden: item.ZK_ISHIDDEN === '1',
          iconCls: item.ZK_ICON,
          leaf: item.ZK_ISLEAF === '1',
          children: this._buildTreeNode(item.ZK_ID, store),
        });
      }
    });
    return obj;
  },

  /**
   * 访问流量
   */
  webAccess() {
    wx.$http.get("/api/start/access");
  }
});